<?php

/// Check that config.php exists, if not then call the install script
if (!file_exists("../../config.php")) {
	echo "Mercurius has not been setup properly.  Please contact the administrator";
	die;
}

require_once ("../../config.php");
$generic_page = true;
include ("../index-incl.php");


$serviceId = required_param('serviceId');
$returnUrl = required_param('returnUrl');
$type = optional_param('type');
$id = optional_param('id');

print_header_simple("",'heading', 'Mercurius');
	print_simple_box_start('center');
	print_heading("Configuring Dash Express with Mercurius");
	echo '<center>';

if(empty($type)) {  // Has not selected type yet
	$msg = "Service ID: $serviceId<br/>User: " . fullname($USER);
	
	print_box($msg);
	print_checkbox("type","simple",true,"Type");
	
	$options = array('serviceId' =>$serviceId,'returnUrl' =>$returnUrl,'type' => 'simple');
	print_single_button($CFG->wwwroot . '/mercurius/dash/configure.php',$options,'Configure','post');
} else if(record_exists('mercurius_dash_settings','userid',$USER->id,'serviceid',$serviceId)) {

	$set = get_record('mercurius_dash_settings', 'userid',$USER->id,'serviceid',$serviceId);
	$set->type = $type;
	
	if(update_record('mercurius_dash_settings',$set)) {
		print_box("Your Mercurius service was already configured.  Updating with type '$type' for service ID: $serviceId.");
		$options = array('serviceId' =>$serviceId,'returnUrl' =>$returnUrl);
		print_single_button($returnUrl,$options,'Return to My Dash','post');
	} else {
		echo "An error occured when trying to update the type ($type)";
	} 	
} else {
	$set = "";
	$set->userid = $USER->id;
	$set->type = $type;
	$set->serviceid = $serviceId;
	
	$retid = insert_record('mercurius_dash_settings', $set, true);
	if(is_numeric($retid) and $retid > 0) {
		print_box("Your Mercurius service of type '$type' has been associated with service ID $serviceId");
		print_single_button($returnUrl,$options,'Return to My Dash','post');
	} else {
		echo "An error occured when trying to associate your Mercurius service (type: $type) with service ID $serviceId.";
	} 
}

echo '</center>';
    print_simple_box_end();
    print_footer();
exit;

?>